package system

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"ruoyi_gin/app/admin/model/system"
	"ruoyi_gin/app/admin/model/tools"
	"ruoyi_gin/utils"
	"ruoyi_gin/utils/R"
	"strconv"
	"time"
)

func ListRole(context *gin.Context) {

	pageNum, _ := strconv.Atoi(context.DefaultQuery("pageNum", "1"))
	pageSize, _ := strconv.Atoi(context.DefaultQuery("pageSize", "10"))

	roleName := context.DefaultQuery("roleName", "")
	roleKey := context.DefaultQuery("roleKey", "")
	status := context.DefaultQuery("status", "")

	beginTime := context.DefaultQuery("params[beginTime]", "")
	endTime := context.DefaultQuery("params[endTime]", "")
	var param = tools.SearchTableDataParam{
		PageNum:  pageNum,
		PageSize: pageSize,
		Other: system.SysRoles{
			RoleName: roleName,
			RoleKey:  roleKey,
			Status:   status,
		},
		Params: tools.ParamsX{
			BeginTime: beginTime,
			EndTime:   endTime,
		},
	}
	var result = system.SelectRoleList(param, true)
	context.JSON(http.StatusOK, result)
}

func GetRoleInfo(ctx *gin.Context) {

	roleId := ctx.Param("roleId")
	userId := ctx.Param("userId")

	if !system.IsAdminById(utils.GetInterfaceToInt(userId)) {
		isCheck := system.CheckRoleDataScope(roleId)

		if isCheck {
			ctx.JSON(http.StatusOK, R.ReturnFailMsg("没有权限访问角色数据！"))

			return
		}
	}

	result := system.FindRoleInfoById(roleId)

	ctx.JSON(http.StatusOK, R.ReturnSuccess(result))
}

func SaveRole(ctx *gin.Context) {

	userId, _ := ctx.Get("userId")

	var rolesParam system.SysRoles

	if err := ctx.ShouldBind(&rolesParam); err != nil {
		ctx.JSON(http.StatusOK, R.ReturnFailMsg("参数不能为空"))

		return
	}

	user := system.FindUseById(userId)
	rolesParam.CreateTime = time.Now()
	rolesParam.CreateBy = user.UserName
	result := system.SaveRole(rolesParam)

	ctx.JSON(http.StatusOK, result)
}
